<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修改密码</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .change-password-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.3);
            padding: 40px;
            width: 100%;
            max-width: 450px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 28px;
            color: #333;
            margin-bottom: 10px;
        }

        .header p {
            color: #666;
            font-size: 14px;
        }

        .user-info {
            background: #f5f5f5;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
            font-size: 14px;
        }

        .user-info strong {
            color: #667eea;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
            font-size: 14px;
        }

        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-group .hint {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }

        .btn {
            width: 100%;
            padding: 14px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 15px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: white;
            color: #667eea;
            border: 2px solid #667eea;
        }

        .btn-secondary:hover {
            background: #f5f5f5;
        }

        .message {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
            font-size: 14px;
        }

        .message.success {
            background: #e8f5e9;
            color: #2e7d32;
            border: 1px solid #4caf50;
        }

        .message.error {
            background: #ffebee;
            color: #c62828;
            border: 1px solid #f44336;
        }

        .message.show {
            display: block;
        }

        .required {
            color: red;
        }

        .password-tips {
            background: #fff3cd;
            padding: 12px;
            border-radius: 8px;
            font-size: 13px;
            color: #856404;
            margin-bottom: 20px;
        }

        .password-tips ul {
            margin: 8px 0 0 20px;
        }

        .password-tips li {
            margin: 3px 0;
        }
    </style>
</head>
<body>
    <div class="change-password-container">
        <div class="header">
            <h1>🔐 修改密码</h1>
            <p>保护您的账户安全</p>
        </div>

        <div class="user-info">
            当前登录：<strong id="currentUsername"></strong>
        </div>

        <div class="password-tips">
            <strong>密码要求：</strong>
            <ul>
                <li>密码长度必须在6-100位之间</li>
                <li>建议使用字母、数字、特殊字符组合</li>
                <li>不要使用过于简单的密码</li>
            </ul>
        </div>

        <div class="message" id="message"></div>

        <form id="changePasswordForm">
            <div class="form-group">
                <label>旧密码 <span class="required">*</span></label>
                <input type="password" id="oldPassword" name="oldPassword" placeholder="请输入当前密码" required autocomplete="current-password">
            </div>

            <div class="form-group">
                <label>新密码 <span class="required">*</span></label>
                <input type="password" id="newPassword" name="newPassword" placeholder="请输入新密码（至少6位）" required autocomplete="new-password">
                <div class="hint">密码长度必须在6-100位之间</div>
            </div>

            <div class="form-group">
                <label>确认新密码 <span class="required">*</span></label>
                <input type="password" id="confirmPassword" name="confirmPassword" placeholder="再次输入新密码" required autocomplete="new-password">
            </div>

            <button type="submit" class="btn btn-primary">修改密码</button>
            <button type="button" class="btn btn-secondary" onclick="window.location.href='home.html'">返回首页</button>
        </form>
    </div>

    <script>
        const API_BASE_URL = '/api/user';

        // 页面加载时检查登录状态
        window.addEventListener('DOMContentLoaded', async () => {
            await checkLoginStatus();
        });

        // 检查登录状态
        async function checkLoginStatus() {
            const token = localStorage.getItem('token');
            const username = localStorage.getItem('username');
            
            if (!token || !username) {
                alert('⚠️ 请先登录');
                window.location.href = '/login.html';
                return;
            }

            // 验证Token
            try {
                const response = await fetch(`${API_BASE_URL}/validate`, {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const result = await response.json();
                
                if (result.code !== 200) {
                    alert('⚠️ 登录已过期，请重新登录');
                    localStorage.clear();
                    window.location.href = '/login.html';
                    return;
                }
                
                // 显示当前用户信息
                document.getElementById('currentUsername').textContent = username;
                
            } catch (error) {
                console.error('验证失败:', error);
                alert('⚠️ 验证失败，请重新登录');
                window.location.href = '/login.html';
            }
        }

        // 表单提交
        document.getElementById('changePasswordForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const token = localStorage.getItem('token');
            const oldPassword = document.getElementById('oldPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            // 前端验证
            if (!oldPassword) {
                showMessage('请输入旧密码', 'error');
                return;
            }
            
            if (!newPassword) {
                showMessage('请输入新密码', 'error');
                return;
            }
            
            if (newPassword.length < 6 || newPassword.length > 100) {
                showMessage('新密码长度必须在6-100位之间', 'error');
                return;
            }
            
            if (newPassword !== confirmPassword) {
                showMessage('两次输入的新密码不一致', 'error');
                return;
            }
            
            if (oldPassword === newPassword) {
                showMessage('新密码不能与旧密码相同', 'error');
                return;
            }
            
            const formData = {
                oldPassword: oldPassword,
                newPassword: newPassword,
                confirmPassword: confirmPassword
            };
            
            try {
                const response = await fetch(`${API_BASE_URL}/change-password`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    },
                    body: JSON.stringify(formData)
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showMessage('✅ 密码修改成功！请使用新密码重新登录...', 'success');
                    
                    // 清除登录信息
                    setTimeout(() => {
                        localStorage.clear();
                        window.location.href = '/login.html';
                    }, 2000);
                } else {
                    showMessage('❌ ' + result.message, 'error');
                }
                
            } catch (error) {
                console.error('修改密码失败:', error);
                showMessage('❌ 修改密码失败：' + error.message, 'error');
            }
        });

        function showMessage(text, type) {
            const messageEl = document.getElementById('message');
            messageEl.textContent = text;
            messageEl.className = `message ${type} show`;
            
            if (type === 'error') {
                setTimeout(() => {
                    messageEl.classList.remove('show');
                }, 5000);
            }
        }
    </script>
</body>
</html>

